package org.cocos2dx.javascript.Voice;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothProfile;
import android.content.Context;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;

import org.cocos2dx.javascript.AppActivity;
import org.cocos2dx.javascript.NativeMgr;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Method;
import static android.content.Context.POWER_SERVICE;
import static com.loopj.android.http.AsyncHttpClient.log;

/*
 * 音频播放的管理类,可调语速
 */
public class AudioMediaManager  {
    private static MediaPlayer player;
    private static boolean isPause;

    private static AudioMediaManager instance;
    private AudioManager audioManager;
    private  boolean mIsFirstEnter;
    private  float playSpeed;


    public  static AudioMediaManager getInstance(){
        if (instance == null){
            synchronized (AudioMediaManager.class){
                if (instance == null)
                {
                    instance = new AudioMediaManager();
                    instance.init();
                }
            }
        }
        return instance;
    }



    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void init(){
        audioManager = (AudioManager) AppActivity.getInstance().getSystemService(Context.AUDIO_SERVICE);
        Log.i("setSpeed init playSpeed", String.valueOf(this.playSpeed));
        this.playSpeed = 1;
    }

   /*
     *  播放声音
     * @param filePath
     * @param listener
     */
    public  void  play(String filePath/*, MediaPlayer.OnCompletionListener listener*/){
        Log.e("playSound","filePath="+filePath);
        if(filePath.equals("")){
            Log.e("playSound", "文件为空");
            return;
        }

        if (player == null) {
            player = new MediaPlayer();
            //设置报错监听
            player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    player.reset();
                    return false;
                }
            });
        }else {
            player.reset();//复位
        }

        try {
 
            this.setPlaySpeaker();
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener () {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    JSONObject mJsonobjData = new JSONObject();
                    NativeMgr.OnCallBackToJs("playAudioFinsh", mJsonobjData.toString());
            }});
            player.setDataSource(filePath);
            player.prepare();
         
            Log.i("setSpeed native", String.valueOf(Build.VERSION.SDK_INT));
            Log.i("setSpeed native",String.valueOf(Build.VERSION_CODES.M));

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                Log.i("setSpeed native play setSpeed", String.valueOf(this.playSpeed));

                PlaybackParams param = player.getPlaybackParams();
                param.setSpeed(this.playSpeed);
                player.setPlaybackParams(param);
            }
           
            player.start();
        }catch (IllegalArgumentException e) {
            Log.e("playSound","IllegalArgumentException ");
            JSONObject mJsonobjData = new JSONObject();
            NativeMgr.OnCallBackToJs("MedioRecordError", mJsonobjData.toString());
            e.printStackTrace();
        } catch (SecurityException e) {
            Log.e("playSound","SecurityException ");
            JSONObject mJsonobjData = new JSONObject();
            NativeMgr.OnCallBackToJs("MedioRecordError", mJsonobjData.toString());
            e.printStackTrace();
        } catch (IllegalStateException e) {
            Log.e("playSound","IllegalStateException ");
            JSONObject mJsonobjData = new JSONObject();
            NativeMgr.OnCallBackToJs("MedioRecordError", mJsonobjData.toString());
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("playSound","IOException ");
            JSONObject mJsonobjData = new JSONObject();
            NativeMgr.OnCallBackToJs("MedioRecordError", mJsonobjData.toString());

            e.printStackTrace();
        }
    }

    private void setPlaySpeaker() {

        boolean isWire = audioManager.isWiredHeadsetOn();
        boolean isBlueTooth = checkBluetoothConn();
        Log.i("audioManager.isWiredHeadsetOn()",  String.valueOf(isWire));
        Log.i("checkBluetoothConn()", String.valueOf(isBlueTooth) );

        try {
            if (isBlueTooth) {      //蓝牙
                audioManager.setMode(AudioManager.MODE_NORMAL);
                audioManager.setSpeakerphoneOn(false);
            } else if  (isWire) {       //有线
                audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
                audioManager.setSpeakerphoneOn(false);
            } else {   
                Log.i("normal MODE_NORMAL" , "setSpeakerphoneOn(true)" );
                audioManager.setSpeakerphoneOn(true);
                audioManager.setMode(AudioManager.MODE_NORMAL);

            }
        } catch (Exception e) {
            JSONObject mJsonobjData = new JSONObject();
            NativeMgr.OnCallBackToJs("MedioRecordError", mJsonobjData.toString());
            e.printStackTrace();
        }

    }

    public  void pause(){
        if (player!= null && player.isPlaying()) {
            player.pause();
            isPause = true;
        }
    }

    public  void  resume(){
        if (player != null && isPause) {
            player.start();
            isPause = false;
        }
    }

    public  void release(){
        if (player != null) {
            player.release();
            player = null;
        }
    }

    public boolean isPlaying(){
        return player!=null && player.isPlaying();
    }

    public  void stop(){
        if (player != null && player.isPlaying()) {
            player.stop();
        }
		    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void setPlaySpeed(String speed) {
        float fs = Float.parseFloat(speed);
        Log.i("setSpeed native speed=",  speed);
        if (player == null) {
            this.playSpeed = fs;
        }
        else {
            this.playSpeed = fs;
        }
    }

    private boolean checkBluetoothConn( ) {
        BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
        if (ba == null) {
            return false;
        } else if (ba.isEnabled()) {
            // 获取三个蓝牙配置文件的连接状态
            int a2dp = ba.getProfileConnectionState(BluetoothProfile.A2DP);             // A2DP（音频传输）
            int headset = ba.getProfileConnectionState(BluetoothProfile.HEADSET);       // HEADSET（蓝牙耳机）
            int health = ba.getProfileConnectionState(BluetoothProfile.HEALTH);         // HEALTH（蓝牙穿戴设备）

            // 如果至少有一个配置文件连接成功，认为蓝牙设备已连接
            if (a2dp == BluetoothProfile.STATE_CONNECTED || 
                headset == BluetoothProfile.STATE_CONNECTED || 
                health == BluetoothProfile.STATE_CONNECTED) {
                return true;
            }
        }
        return false;
        
    }

}
